package __web

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"path/filepath"
)

func GetUserName(c *gin.Context) {
	log.Println("get username...")
	// 路由参数
	name := c.Param("name")
	// 查询参数
	firstname := c.DefaultQuery("firstname", "Guest")
	c.String(http.StatusOK, "Hello %s %s", firstname, name)
}

func GetUserAction(c *gin.Context) {
	name := c.Param("name")
	action := c.Param("action")
	message := name + " is " + action
	// 获取header
	token := c.GetHeader("token")
	c.String(http.StatusOK, "%s\n%s", message, token)
}

func PostUserAction(c *gin.Context) {
	// 获取路由
	b := c.FullPath() == "/user/:name/*action" // true
	// 获取表单参数
	message := c.PostForm("message")
	// 表单参数的键值对
	names := c.PostFormMap("names")
	c.String(http.StatusOK, "%t %s %v", b, message, names)
}

func GetUserGroup(c *gin.Context) {
	// 查询参数的键值对
	ids := c.QueryMap("ids")
	c.String(http.StatusOK, "The available groups are [%v]", ids)
}

// UploadImage 单个文件上传
// 上传文件指令
// curl -X POST http://localhost:8080/upload \
//   -F "file=@/Users/appleboy/test.zip" \
//   -H "Content-Type: multipart/form-data"
func UploadImage(c *gin.Context) {
	// 获取键
	file, _ := c.FormFile("file")
	wd, _ := os.Getwd()
	dstName := filepath.Join(wd, "assert", "123.jpeg")
	// 保存到本地
	err := c.SaveUploadedFile(file, dstName)
	if err != nil {
		log.Println(err)
	}
	c.String(http.StatusOK, "OK")

	// 多个文件
	// form, _ := c.MultipartForm()
	// 	files := form.File["upload[]"]
	// 	for _, file := range files {
	// 		log.Println(file.Filename)
	// 		// Upload the file to specific dst.
	// 		c.SaveUploadedFile(file, dst)
	// 	}
}

// Login Binding from JSON
// 可以解析多种格式:Json、表单和xml
type Login struct {
	User     string `form:"user" json:"user" xml:"user"  binding:"required"`
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

func BindJson(c *gin.Context) {
	var json Login
	// 解析Json
	if err := c.ShouldBindJSON(&json); err != nil {
		// 解析表单
		// if err := c.ShouldBind(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	if json.User != "manu" || json.Password != "123" {
		c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
}
